package org.csu.onlineedubackend.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.csu.onlineedubackend.entity.CommentReply;
import org.csu.onlineedubackend.mapper.CommentReplyMapper;
import org.csu.onlineedubackend.service.CommentReplyService;
import org.csu.onlineedubackend.service.UserService;
import org.csu.onlineedubackend.dto.CommentReplyTreeDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class CommentReplyServiceImpl extends ServiceImpl<CommentReplyMapper, CommentReply> implements CommentReplyService {

    @Autowired
    private UserService userService;

    @Override
    public List<CommentReply> listByCommentId(Integer commentId) {
        return this.list(new QueryWrapper<CommentReply>().eq("comment_id", commentId).orderByAsc("created_at"));
    }

    @Override
    public List<CommentReplyTreeDTO> getReplyTreeByCommentId(Integer commentId) {
        List<CommentReply> all = listByCommentId(commentId);

        // 1. 批量查所有涉及到的userId
        Set<Integer> userIds = all.stream().map(CommentReply::getUserId).collect(Collectors.toSet());
        Map<Integer, String> userNameMap = userService.getUserNamesByIds(userIds);

        // 2. 构建树结构并传入userName
        Map<Integer, CommentReplyTreeDTO> map = new HashMap<>();
        List<CommentReplyTreeDTO> roots = new ArrayList<>();
        for (CommentReply r : all) {
            String userName = userNameMap.getOrDefault(r.getUserId(), "用户");
            CommentReplyTreeDTO dto = new CommentReplyTreeDTO(r, userName);
            map.put(r.getId(), dto);
        }
        for (CommentReply r : all) {
            if (r.getParentReplyId() == null) {
                roots.add(map.get(r.getId()));
            } else {
                CommentReplyTreeDTO parent = map.get(r.getParentReplyId());
                if (parent != null) {
                    parent.getChildren().add(map.get(r.getId()));
                }
            }
        }
        return roots;
    }
}